package top.kangyaocoding.tech.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.ai.chat.messages.Message;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import top.kangyaocoding.tech.common.MessageRedisSerializer;

/**
 * 描述: Redis配置
 *
 * @author K·Herbert
 * @since 2025-04-13 23:10
 */

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Message> messageRedisTemplate(RedisConnectionFactory factory, Jackson2ObjectMapperBuilder builder) {
        if (factory == null || builder == null) {
            throw new IllegalArgumentException("RedisConnectionFactory or Jackson2ObjectMapperBuilder cannot be null");
        }

        try {
            RedisTemplate<String, Message> template = new RedisTemplate<>();
            template.setConnectionFactory(factory);

            // 使用复用的 MessageRedisSerializer 实例
            MessageRedisSerializer serializer = createMessageRedisSerializer(builder.build());

            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(serializer);

            template.setHashKeySerializer(new StringRedisSerializer());
            template.setHashValueSerializer(serializer);

            template.afterPropertiesSet();
            return template;
        } catch (Exception e) {
            // 记录异常日志并抛出自定义异常
            throw new RuntimeException("Failed to initialize RedisTemplate", e);
        }
    }

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper().registerModule(new JavaTimeModule());
    }

    private MessageRedisSerializer createMessageRedisSerializer(ObjectMapper objectMapper) {
        if (objectMapper == null) {
            throw new IllegalArgumentException("ObjectMapper cannot be null");
        }
        return new MessageRedisSerializer(objectMapper);
    }
}
